package com.cb2.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * <a href='https://leetcode.cn/problems/permutations/'>全排列(Permutations)</a>
 * <p>给定一个不含重复数字的数组 nums ，返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。</p>
 * <p>你可以按 任何顺序 返回答案。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,2,3]
 *      输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 *
 * 示例 2：
 *      输入：nums = [0,1]
 *      输出：[[0,1],[1,0]]
 *
 * 示例 3：
 *      输入：nums = [1]
 *      输出：[[1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= nums.length <= 6</li>
 *         <li>-10 <= nums[i] <= 10</li>
 *         <li>nums 中的所有整数 互不相同</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @see LC0046Permutations_M 全排列(Permutations)
 * @see LC0047Permutations_II_M 全排列 II(Permutations II)
 * @since 2025/2/13 15:05
 */
public class LC0046Permutations_M {
    static class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> resList = new ArrayList<>();
            boolean[] visited = new boolean[6];
            backtracking(nums, visited, new ArrayList<>(), resList);
            return resList;
        }

        private void backtracking(int[] nums, boolean[] visited, List<Integer> path, List<List<Integer>> resList) {
            if (path.size() == nums.length) {
                resList.add(new ArrayList<>(path));
                return;
            }
            for (int currIdx = 0; currIdx < nums.length; currIdx++) {
                if (visited[currIdx]) {
                    continue;
                }
                visited[currIdx] = true;
                path.add(nums[currIdx]);
                backtracking(nums, visited, path, resList);
                visited[currIdx] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Printer.printListListInteger(solution.permute(new int[]{1, 2, 3}));
        Printer.printListListInteger(solution.permute(new int[]{0, 1}));
        Printer.printListListInteger(solution.permute(new int[]{1}));
    }
}
